package com.bubblegumproject.ogo.action;

import java.util.Map;
import java.util.HashMap;

/**
 * Base implementation of the {@link Context} interface.
 *
 * @author Azubuko Obele (buko.obele@gmail.com)
 */
public class SimpleContext implements Context {

    private Context parent;

    private String name;

    private Map<String, Object> data = new HashMap<String, Object>();

    public SimpleContext(Context parent) {
        this.parent = parent;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public Context getParent() {
        return parent;
    }

    /**
     * Change the parent of the Context. Clients must be careful how this method is used especially in heavily
     * multithreaded situations.
     *
     * @param parent new parent for the context
     */
    public void setParent(Context parent) {
        this.parent = parent;
    }

    public void set(String key, Object o) {
        assert(key != null);
        data.put(key, o);
    }

    public Object get(String key) {
        assert(key != null);
        Object value = data.get(key);
        if (value != null) {
            return value;
        } else if (parent != null) {
            return parent.get(key);
        } else {
            return null;
        }
    }

    public Map<String, Object> getData() {
        return data;
    }

    public String toString() {
        return "[" + name + " data=" + data + " parent=" + parent + "]";
    }
}
